import { Form, Input } from 'antd';
import { forwardRef, useEffect, useImperativeHandle } from 'react';
import { IMatterFormProps, TMatterRef } from './interface';

const rules = (text: string) => {
  return [{ required: true, message: `请输入${text}` }];
};

const AddOrEditMatterForm = forwardRef<TMatterRef, IMatterFormProps>((props, ref) => {
  const [form] = Form.useForm();
  const { type, groupId, groupName } = props;
  const onSubmit = () => {
    return form
      .validateFields()
      .then((val) => {
        const finalValues = { ...val, type };
        if (type === 'edit') {
          finalValues.groupId = groupId;
        }
        return Promise.resolve(finalValues);
      })
      .catch((err) => {
        // message.error(' AddOrEditMatterForm ERR ');
        // return Promise.reject(err); // 这东西会报错UNcaught (in promise) {values: {…}, errorFields: Array(1), outOfDate: false}
        return console.log(JSON.stringify(err));
      });
  };

  useEffect(() => {
    if (type === 'edit' && groupId) {
      form.setFieldsValue({ groupName });
    }
  }, [type]);

  useImperativeHandle(ref, () => ({
    onSubmit,
  }));

  return (
    <div style={{ padding: '16px 16px 0' }}>
      <Form layout="horizontal" form={form}>
        <Form.Item name="groupName" label="事项名称" rules={rules('30字以内事项名称')}>
          <Input maxLength={30} placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
});

export default AddOrEditMatterForm;
